//***********************************************************************
// FILE: Timer.c
// AUTHOR: Yuriy Skriyka
// DATE: 27-03-2012 
// DESCRIPTION: The file contains implementation of the basic timer. 
//************************************************************************

#include "Timer.h"
#include <avr/interrupt.h>
#include <avr/io.h>

static volatile uint32_t timer = 0;

// ----------------------------------------------------------------------------

ISR(TIM0_COMPA_vect)
{
   timer++;
}

// ----------------------------------------------------------------------------
/*
void initTimer(void)
{
   TCCR0A = _BV(WGM01);       // clear timer on compare match mode

   TCCR0B = _BV(CS01) | _BV(CS00);  // F/64 prescaler

   // TCNT0 = 0;  // it's zero by default

   OCR0A = 150;      // each 150 tick of the timer equals 1ms interval

   TIMSK0 = _BV(OCIE0A);   // enable compare interrupt for OCR0A
}
*/
// ----------------------------------------------------------------------------

uint32_t getTimer(void)
{
   uint32_t mseconds;
   uint8_t sreg = SREG;

   cli();

   mseconds = timer;

   SREG = sreg;

   return mseconds;
}

// ----------------------------------------------------------------------------

void timerSleep(uint32_t milliseconds)
{
   uint32_t startTime = getTimer();

   while ( (startTime + milliseconds) > getTimer() );
}